#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# Magpie - an open source discussion forum system.
#
# Copyright (C) 2009 The Magpie Team
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import logging, os, sys

from google.appengine.dist import use_library
use_library('django', '1.0')

from django.conf import settings
settings._target = None
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import django.core.handlers.wsgi
import django.core.signals
import django.db
import django.dispatch.dispatcher

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

def log_exception(*args, **kwds):
  cls, err = sys.exc_info()[:2]
  logging.exception('Exception in request: %s: %s', cls.__name__, err)

# Log errors.
django.core.signals.got_request_exception.connect(
   log_exception)

# Unregister the rollback event handler.
django.core.signals.got_request_exception.disconnect(
    django.db._rollback_on_exception)

sys.modules[settings.__module__].__file__ = os.path.join(
  os.path.dirname(settings.LOCALE_PATHS[0]), '__init__.py'
)

def real_main():
  application = django.core.handlers.wsgi.WSGIHandler()
  util.run_wsgi_app(application)

def profile_main():
  """Profiles the performance. 
  Appends statistics to the end of pages generated
  """
  import cProfile, pstats
  prof = cProfile.Profile()
  prof = prof.runctx("real_main()", globals(), locals())
  print "<pre>"
  stats = pstats.Stats(prof)
  stats.sort_stats("time")
  stats.print_stats(10)
  print "</pre>"
  
main = real_main

if __name__ == '__main__':
  main()
